package cn.akaba.yun.appCls;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AppRequest {
    private URL url;
    public AppRequest(String urlStr) {
        URL zUrl;
        try {
            zUrl = new URL(urlStr);
        } catch (MalformedURLException malformedURLException) {
            malformedURLException.printStackTrace();
        }
    }
    public static InputStream doRequest(String urlStr) {
        return AppRequest.doRequest(urlStr, "GET");
    }
    public static InputStream doRequest(String urlStr, String requestMethod) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(requestMethod);
            return connection.getInputStream();
        } catch (IOException ioError) {
            ioError.printStackTrace();
            System.out.println("connection error");
        }
        return null;
    }

    public static String getRequestString(String urlStr) {
        return AppRequest.getRequestString(urlStr, "GET");
    }

    public static String getRequestString(String urlStr, String requestMethod) {
        InputStream inputStream = AppRequest.doRequest(urlStr, requestMethod);
        if (inputStream == null) {
            return "";
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder resultText = new StringBuilder();
        while(true) {
            String newStr;
            try {
                newStr = bufferedReader.readLine();
            } catch (Exception err) {
                err.printStackTrace();
                return "";
            }
            if (newStr == null) {
                break;
            }
            resultText.append(newStr);
        }
        return resultText.toString();
    }
}
